package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import core.Square;

public class ClickHandler extends MouseAdapter {
	JLabel label;
	int i, j;

	ClickHandler(JLabel label, int i, int j) {
		this.label = label;
		this.i = i;
		this.j = j;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		super.mouseClicked(e);

		if (e.getButton() == MouseEvent.BUTTON1) {
			/* assert the agent is not on this square */
			if (GridPanel.env.agent.x == i/2 && GridPanel.env.agent.y == j)
				return;
			/* make this square of the current type */
			if(i % 2 == 0)
				GridPanel.env.floor.set(i/2, j, GridPanel.currType);
			else
				GridPanel.env.floor.set(i/2 - 1/2, j, GridPanel.currType);
			label.setIcon(GridPanel.currIcon);
		} else if (e.getButton() == MouseEvent.BUTTON3) {
			/* show a popup menu to choose what to insert */
			JPopupMenu menu = new JPopupMenu();
			
			JMenuItem flower = new JMenuItem("Flowers");
			flower.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					GridPanel.currType = Square.Type.flowers;
					GridPanel.currIcon = GridPanel.flowerIcon;
				}
			});
			
			JMenuItem tile = new JMenuItem("Tile");
			tile.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					GridPanel.currType = Square.Type.clean;
					GridPanel.currIcon = GridPanel.tileIcon;
				}
			});
			
			JMenuItem table = new JMenuItem("Table");
			table.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					GridPanel.currType = Square.Type.table;
					GridPanel.currIcon = GridPanel.tableIcon;
				}
			});
			
			JMenuItem smoking = new JMenuItem("Smoking");
			smoking.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					GridPanel.currType = Square.Type.smoking;
					GridPanel.currIcon = GridPanel.smokingIcon;
				}
			});
			
			JMenuItem meal = new JMenuItem("Meal");
			meal.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					GridPanel.currType = Square.Type.meal;
					GridPanel.currIcon = GridPanel.mealIcon;
				}
			});
			
			menu.add(tile);
			menu.add(flower);
			menu.add(table);
			menu.add(smoking);
			menu.add(meal);
			menu.show(label, e.getX(), e.getY());
		}
	}
}